<template>
  <div class="package-manage">
    <div class="header">
      <el-button type="primary" @click="showCreateDialog" :icon="Plus">上传安装包</el-button>
    </div>
    <el-table :data="packageStore.packages" style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="fileName" label="文件名" show-overflow-tooltip></el-table-column>
      <el-table-column prop="version" label="版本号" width="120"></el-table-column>
      <el-table-column prop="suffix" label="后缀名" width="100"></el-table-column>
      <el-table-column prop="fileSize" label="文件大小" width="150">
        <template #default="{ row }">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="iconUrl" label="图标URL" show-overflow-tooltip></el-table-column>
      <el-table-column prop="officialUrl" label="官网URL" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="showEditDialog(row)"
            :icon="Edit"
          >修改</el-button>
          <el-button
            type="danger"
            size="small"
            @click="packageStore.deletePackage(row.id)"
            :icon="Delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="packageStore.total"
      layout="total, prev, pager, next"
      @current-change="fetchPackages"
      class="pagination"
    />

    <!-- 上传安装包对话框 -->
    <el-dialog title="上传安装包" v-model="createDialogVisible" width="30%">
      <el-form :model="createForm" label-width="80px" :rules="formRules" ref="createFormRef">
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <el-button type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="文件名" v-if="fileName">
          <el-input v-model="fileName" readonly>
            <template #append>
              <el-button @click="copyFileName">复制</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="createForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="官网URL" prop="officialUrl">
          <el-input v-model="createForm.officialUrl" placeholder="请输入官网URL"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="createPackage" :icon="Plus" :loading="uploading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改安装包对话框 -->
    <el-dialog title="修改安装包" v-model="editDialogVisible" width="30%">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editFormRef">
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="editForm.fileName" placeholder="请输入文件名"></el-input>
        </el-form-item>
        <el-form-item label="文件路径" prop="filePath">
          <el-input v-model="editForm.filePath" placeholder="请输入文件路径"></el-input>
        </el-form-item>
        <el-form-item label="文件大小" prop="fileSize">
          <el-input v-model.number="editForm.fileSize" placeholder="请输入文件大小（字节）"></el-input>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-input v-model="editForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item label="后缀名" prop="suffix">
          <el-input v-model="editForm.suffix" placeholder="请输入后缀名"></el-input>
        </el-form-item>
        <el-form-item label="图标URL" prop="iconUrl">
          <el-input v-model="editForm.iconUrl" placeholder="请输入图标URL"></el-input>
        </el-form-item>
        <el-form-item label="官网URL" prop="officialUrl">
          <el-input v-model="editForm.officialUrl" placeholder="请输入官网URL"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePackage" :icon="Edit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { usePackageStore } from '@/stores/api/package';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, type FormInstance, type FormRules, type UploadInstance, type UploadFile } from 'element-plus';
import { useClipboard } from '@vueuse/core';

const packageStore = usePackageStore();
const userStore = useUserStore();
const { copy } = useClipboard();

const createDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const uploading = ref(false);
const fileName = ref('');
const uploadRef = ref<UploadInstance>();

const createForm = ref({
  file: null as File | null,
  version: '',
  officialUrl: '',
});

const editForm = ref({
  id: 0,
  fileName: '',
  filePath: '',
  fileSize: 0,
  version: '',
  suffix: '',
  iconUrl: '',
  officialUrl: '',
});

const formRules = ref<FormRules>({
  file: [{ required: true, message: '请选择文件', trigger: 'change' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  officialUrl: [{ required: true, message: '请输入官网URL', trigger: 'blur' }],
});

const editFormRules = ref<FormRules>({
  fileName: [{ required: true, message: '请输入文件名', trigger: 'blur' }],
  filePath: [{ required: true, message: '请输入文件路径', trigger: 'blur' }],
  fileSize: [
    { required: true, message: '请输入文件大小', trigger: 'blur' },
    { type: 'number', message: '文件大小必须为数字', trigger: 'blur' },
  ],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  suffix: [{ required: true, message: '请输入后缀名', trigger: 'blur' }],
  iconUrl: [{ required: true, message: '请输入图标URL', trigger: 'blur' }],
  officialUrl: [{ required: true, message: '请输入官网URL', trigger: 'blur' }],
});

const createFormRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
};

const handleFileChange = (file: UploadFile) => {
  createForm.value.file = file.raw || null;
  fileName.value = file.name;
};

const handleFileRemove = () => {
  createForm.value.file = null;
  fileName.value = '';
};

const copyFileName = async () => {
  try {
    await copy(fileName.value);
    ElMessage.success('文件名已复制');
  } catch (error) {
    ElMessage.error('复制失败');
  }
};

const fetchPackages = async () => {
  try {
    await packageStore.fetchPackages(currentPage.value - 1, pageSize.value);
  } catch (error: any) {
    ElMessage.error('获取安装包列表失败: ' + error.message);
  }
};

const showCreateDialog = () => {
  createForm.value = {
    file: null,
    version: '',
    officialUrl: '',
  };
  fileName.value = '';
  createDialogVisible.value = true;
};

const createPackage = async () => {
  if (!createFormRef.value) return;
  createFormRef.value.validate(async (valid) => {
    if (valid && createForm.value.file) {
      try {
        uploading.value = true;
        const formData = new FormData();
        formData.append('file', createForm.value.file);
        formData.append('version', createForm.value.version);
        formData.append('officialUrl', createForm.value.officialUrl);
        await packageStore.uploadPackage(formData);
        createDialogVisible.value = false;
        currentPage.value = 1; // 重置为第一页
        await fetchPackages();
        ElMessage.success('上传成功');
      } catch (error: any) {
        ElMessage.error('上传失败: ' + error.message);
      } finally {
        uploading.value = false;
      }
    }
  });
};

const resetForm = () => {
  createDialogVisible.value = false;
  uploadRef.value?.clearFiles();
  fileName.value = '';
};

const showEditDialog = (pkg: any) => {
  editForm.value = { ...pkg, id: pkg.id };
  editDialogVisible.value = true;
};

const updatePackage = async () => {
  if (!editFormRef.value) return;
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await packageStore.updatePackage(editForm.value);
        editDialogVisible.value = false;
        currentPage.value = 1; // 重置为第一页
        await fetchPackages();
        ElMessage.success('更新成功');
      } catch (error: any) {
        ElMessage.error('更新失败: ' + error.message);
      }
    }
  });
};

onMounted(() => {
  fetchPackages();
});
</script>

<style scoped>
.package-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.el-button i + span {
  margin-left: 8px;
}
.el-select {
  width: 100%;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>